import React from 'react';

import router from '../../../utils/routerDecorator';
import {get, post} from '../../../logic/api';
import ObjectList from '../../components/ObjectList';

import Edit from './Edit';
import Del from './Del';

import styles from './main.less';

@router('/site/goods')
export default class Goods extends React.Component {

  state = {
    loading:true
  }

  cates = {};
  catesTree = [];

  async componentWillMount(){
    //获取分类信息
    var ret = await get('/admin/cate/list/main');

    var data = ret.data.content;
    for(var i=0;i<data.length;i++){
      this.cates[data[i].id] = data[i].cname;
      this.catesTree.push({
        value:data[i].id+"",
        label:data[i].cname,
        children:[]
      })

      for(var j=0;j<data[i].children.length;j++){
        this.cates[data[i].children[j].id] = data[i].children[j].cname;
        this.catesTree[i].children.push({
          value:data[i].children[j].id+"",
          label:data[i].children[j].cname
        })
      }
    }

    this.setState({
      loading:false
    })
  }

  async fetchData(current, pageSize, filters, sorter){
    return await get('/admin/goods/list/' + current + "/" + pageSize);
  }

  genColumns(){
    return [
      {title:'中文名称', dataIndex:'cname', width:'20%'},
      {title:'英文名称', dataIndex:'ename', width:'20%'},
      {title:'图片', dataIndex:'image', width: '15%', render:(hash)=>{
        return <img src = {"http://oalpta27j.bkt.clouddn.com/"+hash} style ={{width:50}}></img>
      }},
      {title:'原价', dataIndex:'oprice', width:'10%'},
      {title:'现价', dataIndex:'nprice', width:'10%'},
      {title:<div>
          <span>操作</span>
          <span>
            <Edit text = "新建" fetchData = {()=>{
              return {
                data:{
                  cateId:["1"],
                  ename:"",
                  cname:"",
                  image:"",
                  nprice:"0",
                  oprice:"0",
                  describe:"",
                  images3:"[]",
                  detailtitle:"",
                  detail:"",
                  particular:"",
                  notice:""
                }
              }
            }} catesTree = {this.catesTree} record = {{id:0}} reload = {()=>{
              ObjectList.Emitter.emit("reload");
            }}/>
          </span>   
        </div>,
       
       width:'25%', render:(text, record)=>{
        return <div className = {styles.operations}>
          <Edit record = {record} catesTree = {this.catesTree} reload = {()=>{
            ObjectList.Emitter.emit("reload");
          }}/>
          <Del record = {record} reload = {()=>{
            ObjectList.Emitter.emit("reload");
          }}/>
        </div>
      }}
    ]
  }
  
  render(){
    if (this.state.loading) {
      return <div/>
    }

    return <div>
      <ObjectList 
        columns = {this.genColumns()}
        fetchData = {this.fetchData}
      />
    </div>
  }
}